import { ContextOptions, createAxios } from '../http/axios';
import { useMessage } from '@shared/hooks/web/useMessage';
import { getEnv, isDevMode } from '../env';
import { VAxios } from '../http/axios/src/Axios';
import { useUserStoreWithOut } from '@/shared/store/user';
import { message } from 'ant-design-vue';
import logger from '@shared/utils/logger';

function getDefaultRequestContextOptions(): ContextOptions {
  const { createMessage, createErrorModal } = useMessage();

  return {
    getTokenFunction() {
      const userStore = useUserStoreWithOut();
      return userStore.getTokenData;
    },
    getRefreshTokenFunction() {
      //
      return '';
    },
    // @ts-ignore
    refreshTokenFunction() {
      //
    },
    /**
     * NOTE: 新增了 refreshToken 功能后，403 由后端定义专门用来处理 token 过期的状态码，具体由什么原因导致的 403，由 data.code 字段来区分
     * 此处新增的 refreshTokenErrorFunction 是为了防止后期后端修改了 403 的含义，导致前端无法正常处理，如果 403 的定义不变，可以直接使用 httpForbiddenFunction 来处理
     */
    refreshTokenErrorFunction() {
      //
    },
    // http status 401 用户身份过期
    httpUnauthorizedFunction(_response, _message) {
      const { url, params, data, headers } = _response.config;
      logger.info('----- httpUnauthorizedFunction fn >>> 用户身份过期，请求如下 -----', _message, {
        url,
        params,
        data,
        headers,
        currentUser: useUserStoreWithOut().userData
      });

      message.destroy();
      const userStore = useUserStoreWithOut();
      userStore.logoutAction();
    },
    // http status 403
    httpForbiddenFunction(_response, _message) {
      //
    },
    handleHttpStateErrorFunction(_response, message, errorMessageMode) {
      if (errorMessageMode === 'modal') {
        createErrorModal({ title: '错误提示', content: message });
      }
      if (errorMessageMode === 'message') {
        createMessage.error(message);
      }
    },
    // code 401 用户身份过期
    unauthorizedFunction(_response, _message) {
      const userStore = useUserStoreWithOut();
      userStore.logoutAction();
    },
    // code 403 没有权限
    forbiddenFunction(_response, _message) {
      // some code
    },
    errorModalFunction(_response, { title, content }) {
      createErrorModal({
        title: title || '错误提示',
        content
      });

      const { url, params, data, headers } = _response.config;
      logger.info(
        '----- errorModalFunction fn >>> 请求error 类型ModelError，请求如下 -----',
        `${content}  |  ${content}`,
        {
          url,
          params,
          data,
          headers,
          currentUser: useUserStoreWithOut().userData
        }
      );
    },
    errorMessageFunction(_response, message) {
      createMessage.error(message);

      const { url, params, data, headers } = _response.config;
      logger.info(
        '----- errorMessageFunction fn >>> 请求error 类型MessageError，请求如下 -----',
        message,
        {
          url,
          params,
          data,
          headers,
          currentUser: useUserStoreWithOut().userData
        }
      );
    }
  };
}

function _defaultRequest(): VAxios {
  const {
    RENDERER_VITE_DEFAULT_REQUEST_URL,
    RENDERER_VITE_DEFAULT_REQUEST_URL_PREFIX,
    RENDERER_VITE_DEFAULT_REQUEST_URL_PROXY_PREFIX
  } = getEnv();
  return createAxios({
    requestOptions: {
      applyUrlPrefix: true,
      urlPrefix: RENDERER_VITE_DEFAULT_REQUEST_URL_PREFIX,
      baseApiUrl: () => {
        if (isDevMode() && RENDERER_VITE_DEFAULT_REQUEST_URL_PROXY_PREFIX) {
          return RENDERER_VITE_DEFAULT_REQUEST_URL_PROXY_PREFIX;
        }
        return RENDERER_VITE_DEFAULT_REQUEST_URL;
      }
    },
    contextOptions: getDefaultRequestContextOptions()
  });
}

export const defaultRequest = _defaultRequest();
